<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { CircleCheck, CircleClose, View, DocumentCopy } from '@element-plus/icons-vue';
import { ElAvatar, ElSwitch, ElButton, ElPagination, ElMessage } from 'element-plus';
import { userListService } from '@/api/user.js';
import defaultAvatar from '@/assets/my.jpg';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();

// 定义用户数据类型
interface User {
    id: number;
    nickname: string;
    status: 0 | 1; // 1 表示封禁，0 表示正常
    createTime: string; // ISO 时间戳字符串
    avatar: string; // 用户头像 URL
    openId: string; // 用户的唯一开放 ID
}

// 定义状态映射
const STATUS_MAP: Record<number, { type: string; text: string; color: string }> = {
    1: { type: 'danger', text: '封禁', color: '#F56C6C' },
    0: { type: 'success', text: '正常', color: '#409EFF' },
};

// 数据定义
const data = ref<User[]>([]); // 用户数据列表
const loading = ref(false); // 加载状态
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页大小
const total = ref(0); // 总数据量

// 格式化日期
const formatDate = (dateString: string) => {
    try {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
        }).replace(/\//g, '-');
    } catch {
        return '未知时间';
    }
};

//处理状态修改
const handleStatusChange = async (isChecked: boolean, row: User) => {
    const newStatus = isChecked ? 0 : 1;
    try {
        // await updateUserStatusService(row.id, newStatus);
        row.status = newStatus;
        ElMessage.success(isChecked ? '用户已解封' : '用户已封禁');
    } catch (error) {
        console.error('更新用户状态失败:', error);
        ElMessage.error(isChecked ? '解封失败' : '封禁失败');
    }
};

// 查看行为详情
const handleViewDetail = (row: User): void => {
    console.log('查看用户行为详情:', row);
    router.push(`/user/analytics?id=${row.id}`)
    // 这里可以添加跳转到详情页面的逻辑
    // ElMessage.info(`查看用户 ${row.nickname} 的详情`);
};

// 查看行为详情
const handleViewLog = (row: User): void => {
    console.log('查看用户行为详情:', row);
    router.push(`/user/log?id=${row.id}`)
    // 这里可以添加跳转到详情页面的逻辑
    // ElMessage.info(`查看用户 ${row.nickname} 的详情`);
};

// 组件挂载时获取数据
onMounted(() => {
    fetchUsers();
});

// 获取用户列表
const fetchUsers = async () => {
    loading.value = true;
    try {
        const params = {
            page: currentPage.value,
            size: pageSize.value,
        };
        const result = await userListService(params);
        data.value = result.data.records;
        total.value = result.data.total;
    } catch (error) {
        console.error('获取用户数据失败:', error);
        ElMessage.error('获取用户数据失败');
    } finally {
        loading.value = false;
    }
};
</script>

<template>
    <div class="user-table-container">
        <!-- 用户表格 -->
        <el-table :data="data" border stripe v-loading="loading" style="width: 100%">
            <!-- ID 列 -->
            <el-table-column prop="id" label="ID" width="80" show-overflow-tooltip />
            <!-- OpenID 列 -->
            <el-table-column prop="openId" label="OpenID" width="150" show-overflow-tooltip />
            <!-- 昵称列 -->
            <el-table-column prop="nickname" label="昵称" width="150" />
            <!-- 头像列 -->
            <el-table-column prop="avatar" label="头像" width="100">
                <template #default="{ row }">
                    <el-avatar :src="row.avatar ? row.avatar : defaultAvatar" fit="cover" />
                </template>
            </el-table-column>
            <!-- 状态列 -->
            <el-table-column prop="status" label="状态" width="150" align="center">
                <template #default="{ row }">
                    <div class="status-switch-container">
                        <el-switch v-model="row.status" :active-value="0" :inactive-value="1" inline-prompt
                            :active-icon="CircleCheck" :inactive-icon="CircleClose" :active-text="STATUS_MAP[0].text"
                            :inactive-text="STATUS_MAP[1].text" :style="{
                                '--el-switch-on-color': STATUS_MAP[0].color,
                                '--el-switch-off-color': STATUS_MAP[1].color
                            }" @change="(val) => handleStatusChange(val === 0, row)" />
                    </div>
                </template>
            </el-table-column>
            <!-- 注册时间列 -->
            <el-table-column prop="createTime" label="注册时间" width="180">
                <template #default="{ row }">
                    {{ formatDate(row.createTime) }}
                </template>
            </el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作">
                <template #default="{ row }">
                    <!-- 查看阅读数据按钮 -->
                    <el-button type="text" size="small" @click="handleViewDetail(row)">
                        <el-icon>
                            <View />
                        </el-icon>
                        阅读数据
                    </el-button>
                    <!-- 查看行为日志按钮 -->
                    <el-button type="text" size="small" @click="handleViewLog(row)">
                        <el-icon>
                            <DocumentCopy />
                        </el-icon>
                        行为日志
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" background
                @size-change="fetchUsers" @current-change="fetchUsers" />
        </div>
    </div>
</template>

<style scoped lang="scss">
.user-table-container {
    .pagination {
        margin-left: auto;
        margin-top: 20px;

        .el-pagination {
            display: flex;
            justify-content: flex-end;
        }
    }
}

.status-switch-container {
    display: flex;
    justify-content: center;

    .el-switch {
        --el-switch-border-color: transparent;

        .el-switch__core {
            height: 26px;
            border-radius: 13px;

            .el-switch__action {
                width: 22px;
                height: 22px;
                top: 2px;
            }
        }

        .el-switch__inner {
            font-size: 12px;
            color: white;
            font-weight: bold;
            padding: 0 8px 0 24px;

            .is-icon {
                display: none; // 隐藏图标只保留文字
            }
        }

        &.is-checked {
            .el-switch__inner {
                padding: 0 24px 0 8px;
            }
        }
    }
}
</style>